import random
import pygame
from config import *
from utils import *

# directions = ["UP", "DOWN", "LEFT", "RIGHT"]
# direction = directions[random.randrange(0, len(directions))]

score = 0
game_status = True

# direction, snake_body = init()
previous_direction = direction
snake_head_pos = snake_body[0]

food_pos, food_spawn = generate_food()

# 初始化 Pygame：
pygame.init()
screen = pygame.display.set_mode((width, height))
print(snake_body)
# 创建游戏主循环，处理事件和更新游戏状态：


while game_status:
    for event in pygame.event.get():
        print(previous_direction, direction)
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
        # 处理按键事件，改变蛇的移动方向：
        elif event.type == pygame.KEYDOWN:
            previous_direction = direction
            if direction == "NONE":
                continue
            if event.key == pygame.K_RIGHT and previous_direction != "LEFT":
                direction = "RIGHT"
            elif event.key == pygame.K_LEFT and previous_direction != "RIGHT":
                direction = "LEFT"
            elif event.key == pygame.K_UP and previous_direction != "DOWN":
                direction = "UP"
            elif event.key == pygame.K_DOWN and previous_direction != "UP":
                direction = "DOWN"
            elif event.key == pygame.K_c:
                cheat_mode = not cheat_mode
            print(previous_direction, direction)
    
    if cheat_mode and direction != "NONE":
        direction = cheat_mode_get_direction(snake_head_pos, food_pos)
    
    # 更新贪吃蛇的位置和身体：
    snake_head_pos = add(snake_head_pos, multiple(directions[direction], grid_width))
    print(snake_head_pos)
    
    # 检查贪吃蛇是否碰到边界或自己的身体：
    if not in_the_area(snake_head_pos, (0, 0), (width, height), grid_width):
        direction = "NONE"
    for block in snake_body[1:]:
        if snake_head_pos == block:
            direction = "NONE"
    
    if direction != "NONE":
        snake_body.insert(0, list(snake_head_pos))
    
    if snake_head_pos == food_pos:
        score += 1
        food_spawn = False
    else:
        if direction != "NONE":
            snake_body.pop()
    
    # 生成新的食物：
    if not food_spawn:
        food_pos, food_spawn = generate_food()
    # 渲染游戏界面：
    screen.fill((0, 0, 0))
    for pos in snake_body:
        pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(pos[0], pos[1], grid_width, grid_width))
    pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(food_pos[0], food_pos[1], grid_width, grid_width))
    
    rander_grid(screen, (0, 0), (width, height))
    
    if direction == "NONE":
        show_message(screen)
    
    pygame.display.set_caption("贪吃蛇游戏 - 得分: " + str(score))
    pygame.display.flip()
    # 控制游戏更新速度：
    pygame.time.Clock().tick(refresh_speed)
